<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 账号管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
			<div class="handle-box">
				<el-button
					type="primary"
					icon="el-icon-plus"
					class="handle-del mr10"
					@click="handleAdd()"
				>添加后台账号</el-button>
			</div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
				style="width: 80%"
            >
                <el-table-column prop="account" width="120" label="账号"></el-table-column>
                <el-table-column prop="role"  label="权限" :formatter="doformatter"></el-table-column>
                <!-- <el-table-column label="状态" width="80" align="center">
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.state==='成功'?'success':(scope.row.state==='失败'?'danger':'')"
                        >{{scope.row.state}}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
                <!-- <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination> -->
            </div>
        </div>

        <!-- 添加账号弹出框 -->
        <el-dialog title="添加账号" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="账号">
                    <el-input v-model="form.account"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="form.password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
		
		<!-- 编辑用户角色弹出框 -->
		<el-dialog title="修改权限" :visible.sync="editVisible" width="40%" >
		    <el-form ref="form" :model="form" label-width="100px">
		        <div class="drag-box">
		            <div class="drag-box-item">
		                <div class="item-title">可添加角色</div>
		                <draggable v-model="todo" :options="dragOptions">
		                    <transition-group tag="div" id="todo" class="item-ul">
		                        <div v-for="item in todo" class="drag-list" :key="item.id">
		                            {{item.content}}
		                        </div>
		                    </transition-group>
		                </draggable>
		            </div>
		            <div class="drag-box-item">
		                <div class="item-title">当前角色</div>
		                <draggable v-model="doing" :options="dragOptions">
		                    <transition-group tag="div" id="doing" class="item-ul">
		                        <div v-for="item in doing" class="drag-list" :key="item.id">
		                            {{item.content}}
		                        </div>
		                    </transition-group>
		                </draggable>
		            </div>
		        </div>
		    </el-form>
		    <span slot="footer" class="dialog-footer">
		        <el-button @click="editVisible = false">取 消</el-button>
		        <el-button type="primary" @click="changeRole()">确 定</el-button>
		    </span>
		</el-dialog>
		
    </div>
</template>

<script>
import { getUser } from '../../api/index';
import { addUser } from '../../api/index';
import { changeUserRole } from '../../api/index';
import { getAllRole } from '../../api/index';
import {deleteUser} from '../../api/index';
import draggable from 'vuedraggable'
import qs from 'qs';
import request from '../../utils/request';

export default {
    name: 'basetable',
    data() {
        return {
            query: {
                name: '',
                page: 0,
                pageSize: 0
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
			addVisible: false,
            pageTotal: 10,
			page:0,
            form: {},
            idx: -1,
            id: -1,
			dragOptions:{
			    animation: 120,
			    scroll: true,
			    group: 'sortlist',
			    ghostClass: 'ghost-style'
			},
			todo: [
				{
			        id: 0,
			        content: '测试数据'
			    },
			],
			doing: [
			    {
			        id: 1,
			        content: '测试数据'
			    },
			],
			roles:{
				uid:'',
				rolesId:[]
			},
        };
    },
	components:{
	    draggable
	},
    created() {
        this.getData();
		console.log(this.todo);
    },
    methods: {
		//修改权限
		changeRole(){
			this.roles.rolesId=[];
			this.doing.forEach((item,i)=>{
				this.roles.rolesId[i]=item.id
			})
			console.log(this.roles.rolesId);
			if(this.roles.rolesId.length<1){
				this.$message.info("至少选择一个权限")
			}else{
				request.post("/user/changerole", qs.stringify(
					this.roles,
					{ indices: false })).then(res=>{
						console.log(res);
						if(res.code!=200){
							this.$message.error(res.status)
						}else{
							this.editVisible=false;
							this.$message.success("修改成功");
							this.getData();
						}
					})
			}
			
		},
		doformatter(row,column){
			let re='';
			row.role.forEach((item,i) => {
				if(row.role.length>i+1){
					re=re+item.role+'，'
				}else{
					re=re+item.role
				}
			})
			
			return re;
		},
        getData() {
            getUser(this.query).then(res => {
                console.log(res);
                this.tableData = res.t;
                this.pageTotal = res.t.pageSize;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
				this.roles.uid=row.id;
					deleteUser(this.roles).then(res=>{
						if(res.code!=200){
							this.$message.error(res.status)
						}else{
							this.$message.success('删除成功');
							this.tableData.splice(index, 1);
						}
					})
                })
                .catch(() => {});
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
		// 编辑操作
		handleEdit(index,row) {
			this.todo=[];
			this.doing=[];
			this.roles.uid=row.id;
			let roles=[];
			row.role.forEach((item,i)=>{
				roles[i]=item.id
			})
			getAllRole().then(res=>{
				let to=0;
				let doin=0;
				res.t.forEach((item,index)=>{
					let role={
						id:item.id,
						content:item.role
					};
					if(roles.includes(item.id)){
						this.doing[doin]=role;
						doin=doin+1;
					}else{
						this.todo[to]=role;
						to=to+1;
					}
				})
				this.editVisible = true;
			})
		},
        // 添加操作
        handleAdd() {
            this.addVisible = true;
        },
        // 确认添加账号
        saveAdd() {
			addUser(this.form)
			.then(res=>{
				this.editVisible = false;
				console.log(res);
				if(res.code==200){
					this.$message.success(`添加成功`);
					this.getData();
					this.addVisible = false;
				}else{
					this.$message.error(res.status);
				}
			}).catch((error)=>{
				this.$message.error(`服务器异常`)
			})
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
/* =============== */
   .drag-box{
        display: flex;
        user-select: none;
    }
    .drag-box-item {
        flex: 1;
        max-width: 250px;
        min-width: 150px;
        background-color: #eff1f5;
        margin-right: 16px;
        border-radius: 6px;
        border: 1px #e1e4e8 solid;
    }
    .item-title{
        padding: 8px 8px 8px 12px;
        font-size: 14px;
        line-height: 1.5;
        color: #24292e;
        font-weight: 600;
    }
    .item-ul{
        padding: 0 8px 8px;
        height: 300px;
        overflow-y: scroll;
    }
    .item-ul::-webkit-scrollbar{
        width: 0;
    }
    .drag-list {
        border: 1px #e1e4e8 solid;
        padding: 10px;
        margin: 5px 0 10px;
        list-style: none;
        background-color: #fff;
        border-radius: 6px;
        cursor: pointer;
        -webkit-transition: border .3s ease-in;
        transition: border .3s ease-in;
    }
    .drag-list:hover {
        border: 1px solid #20a0ff;
    }
    .drag-title {
        font-weight: 300;
        line-height: 25px;
        margin: 10px 0;
        font-size: 22px;
        color: #1f2f3d;
    }
    .ghost-style{
        display: block;
        color: transparent;
        border-style: dashed
    }
</style>
